# services/random_avatar_service.py
import random

from sqlalchemy import select, func
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm.session import Session

from common.sqlalchemy_db import SqlalchemyX
from modules.mod import RandomAvatars


class RandomAvatarService:
    def __init__(self,session: AsyncSession = SqlalchemyX.AsyncSessionLocal()):
        self.session  =session

    async def get_random_avatar_url(self) -> str:
        # 使用简单的方法获取总数
        async with self.session as session:
            # 获取总数
            count_query = select(func.count()).select_from(RandomAvatars)
            result = await session.execute(count_query)
            total_count = result.scalar()

            if total_count == 0:
                raise ValueError("没有可用的随机头像")

            random_index = random.randint(0, total_count - 1)

            # 使用原来的查询逻辑，只是改为异步方式
            query = select(RandomAvatars).offset(random_index).limit(1)
            result = await session.execute(query)
            avatar = result.scalars().first()

            if not avatar:
                raise ValueError("未找到指定偏移量的头像数据")

            return avatar.random_avatar_url